using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using SmartLink.DTOS;
using SmartLink.Application.Services;
using SmartLink.EnumLibrary;

namespace SmartLink.WebApi.Controllers
{

    public class FileUploadController : ApiController
    {
        /// <summary>
        /// 图文上传
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public Results<string> ImgUpload()
        {
            string reUrl = "";
            if (HttpContext.Current.Request.Files.Count<= 0)
            {
                return InfrastructureAppService.Response("", "请选择文件！", StateCodeEnum.失败.GetHashCode());
            }
            var fileTest = HttpContext.Current.Request.Files[0].FileName;
            long max = long.Parse(ConfigurationManager.AppSettings["Max"]);
            string fileTypes = ConfigurationManager.AppSettings["fileTypes"];
            
             if (fileTest.Length > max)
            {
                return InfrastructureAppService.Response("","上传文件大小超过限制！", StateCodeEnum.失败.GetHashCode());
            }
            var fileExt = fileTest.Substring(fileTest.LastIndexOf('.'));
            if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(fileTypes.Split(','), fileExt.Substring(1).ToLower()) == -1)
            {
                return InfrastructureAppService.Response("","不支持上传文件类型！", StateCodeEnum.失败.GetHashCode());
            }
            else
            {
                //截取文件名
                string[] fileSpits = fileTest.Split(new string[1] { "\\" }, StringSplitOptions.RemoveEmptyEntries);
                fileTest = fileSpits[fileSpits.Length - 1];
                var pattern = new Regex("[`~!@#$%^&*()+=|{}':;',\\[\\]<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]");
                if (pattern.IsMatch(fileTest))
                {
                return InfrastructureAppService.Response("","文件名不能存在特殊字符！", StateCodeEnum.失败.GetHashCode());
                }
                else
                {
                    //配置文件夹
                    string SaveTempPath = ConfigurationManager.AppSettings["SavePath"];
                    var dirTempPath = HttpContext.Current.Server.MapPath(SaveTempPath);
                    //获得当前日期
                    string dateFolder = DateTime.Now.ToString("yyyyMMdd");
                    fileTest = DateTime.Now.ToString("yyyyMMddHHmmssfff") + fileTest;
                    string lastname = dirTempPath + dateFolder + "/" + fileTest;
                    if (File.Exists(lastname))
                    {
                        return InfrastructureAppService.Response<string>("已经存在相同文件，请不要重复上传！", StateCodeEnum.失败.GetHashCode());
                    }
                    else
                    {
                        string local = ConfigurationManager.AppSettings["BaseUrl"];
                        reUrl = local + dateFolder + "/" + fileTest;
                        //判断是否存在文件夹
                        if (!Directory.Exists(dirTempPath + dateFolder))
                        {
                            //文件夹不存在则创建该文件夹  
                            string name = Directory.CreateDirectory(dirTempPath + dateFolder).ToString();
                            HttpContext.Current.Request.Files[0].SaveAs(lastname);
                        }
                        HttpContext.Current.Request.Files[0].SaveAs(lastname);
                        return InfrastructureAppService.Response<string>(reUrl,"上传成功",1);
                    }
                }
            }
            
        }
    }
}
